package com.jhj.provider.resume.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.jhj.provider.resume.po.b.model.Dict;
import com.jhj.provider.resume.po.b.model.Resume;
import com.jhj.provider.resume.po.b.model.ResumeLog;
import com.jhj.provider.resume.po.b.model.ResumeServiceArea;
import com.jhj.provider.resume.po.b.model.ResumeSkill;
import com.jhj.provider.resume.service.DictService;
import com.jhj.provider.resume.service.ResumeFromService;
import com.jhj.provider.resume.service.ResumeLogService;
import com.jhj.provider.resume.service.ResumeScoreService;
import com.jhj.provider.resume.service.ResumeService;
import com.jhj.provider.resume.service.ResumeServiceAreaService;
import com.jhj.provider.resume.service.ResumeSkillService;
import com.jhj.provider.resume.utils.Constants;
import com.jhj.provider.resume.utils.ResumeUtil;
import com.jhj.provider.resume.vo.ResumeSearchVo;
import com.jhj.utils.AppResultData;
import com.jhj.utils.IdcardInfoExtractor;
import com.jhj.utils.StringUtil;
import com.jhj.utils.TimeStampUtil;


/**
 *
 */
@RestController
public class ResumeUpdateController {
	
	@Autowired
	ResumeService resumeService;
	
	@Autowired
	ResumeScoreService resumeScoreService;
	
	@Autowired
	ResumeLogService resumeLogService;
	
	@Autowired
	ResumeSkillService resumeSkillService;
	
	@Autowired
	ResumeServiceAreaService resumeServiceAreaService;
	
	@Autowired
	ResumeFromService resumeFromService;
	
	@Autowired
	DictService dictService;
	
	/**
	 * 更新人才库
	 * @param resumeNo
	 * @param name
	 * @param sex
	 * @param workYear
	 * @param serviceTypes
	 * @param hopeSalary
	 * @param nationId
	 * @param degreeId
	 * @param fromId
	 * @param fromMobile
	 * @param fromName
	 * @param serviceProvinceId
	 * @param serviceCityId
	 * @param serviceRegionIds
	 * @param provinceId
	 * @param hukou
	 * @param cityId
	 * @param idCard
	 * @param addr
	 * @param remark
	 * @param serviceCanDate
	 * 
	 * @return map
	 * 
	 * */
	@RequestMapping(value = "/api/resume/update.json", method = RequestMethod.POST)
	public AppResultData<Object> update(
		@RequestParam("resumeNo") String resumeNo,
		@RequestParam("name") String name,
		@RequestParam("sex") Integer sex,
		@RequestParam("workYear") Integer workYear,
		@RequestParam("serviceTypes") String serviceTypes,
//		@RequestParam("resumeFrom") Integer resumeFrom,
		@RequestParam(value = "hopeSalary", required = false, defaultValue = "0") Integer hopeSalary,
		@RequestParam(value = "nationId", required = false, defaultValue = "0") Integer nationId,
		@RequestParam(value = "degreeId", required = false, defaultValue = "0") Integer degreeId,
		@RequestParam(value = "fromId", required = false, defaultValue = "0") Integer fromId,
		@RequestParam(value = "fromMobile", required = false, defaultValue = "") String fromMobile,
		@RequestParam(value = "fromName", required = false, defaultValue = "") String fromName,
		@RequestParam(value = "serviceProvinceId", required = false, defaultValue = "0") Integer serviceProvinceId,
		@RequestParam(value = "serviceCityId", required = false, defaultValue = "0") Integer serviceCityId,
		@RequestParam(value = "regionids", required = false, defaultValue = "0") String regionids,
		@RequestParam(value = "provinceId", required = false, defaultValue = "0") Integer provinceId,
		@RequestParam(value = "hukou", required = false, defaultValue = "") String hukou,
		@RequestParam(value = "cityId", required = false, defaultValue = "0") Integer cityId,
		@RequestParam(value = "idCard", required = false, defaultValue = "0") String idCard,
		@RequestParam(value = "addr", required = false, defaultValue = "") String addr,
		@RequestParam(value = "remark", required = false, defaultValue = "") String remark,
		@RequestParam(value = "serviceCanDate", required = false, defaultValue = "") String serviceCanDate
		) {
		AppResultData<Object> result = new AppResultData<Object>(Constants.SUCCESS_0, "ok", "");
		
		//校验1. 判断人才是否存在
		Resume searchVo = new Resume();
		searchVo.setResumeNo(resumeNo);
		Resume resume = resumeService.selectOne(searchVo);
		if (resume == null) {
			result.setStatus(Constants.ERROR_999);
			result.setMsg("人才信息不存在");
			return result;
		}
		Integer resumeId = resume.getResumeId();
		
		//校验2.判断身份证是否已经存在其他的位置.
		if (!StringUtil.isEmpty(idCard) && !idCard.equals(resume.getIdCard())) {
			searchVo = new Resume();
			searchVo.setIdCard(idCard);
			Resume isExistResume = resumeService.selectOne(searchVo);
			if (isExistResume != null) {
				if (isExistResume.getResumeId() != resumeId)
				result.setStatus(Constants.ERROR_999);
				result.setMsg("身份证号码已经注册过.");
				return result;
			}
		}
		
		
		Integer nowTime = TimeStampUtil.getNowSecond().intValue();
		Integer totalScore = resume.getTotalScore();
		//记录修改的日志.
		StringBuilder resumeLogRemark = new StringBuilder("");
		
		if (!resume.getName().equals(name)) {
			resume.setName(name);
			resumeLogRemark.append("姓名" + resume.getName() + "改为" + name + "</BR>");
		}
		
		if (resume.getSex() != sex) {
			resume.setSex(sex);
			resumeLogRemark.append("性别" + ResumeUtil.getSexName(resume.getSex()) + "改为" + ResumeUtil.getSexName(sex) + "</BR>");
		}
		
		Dict dictSearchVo = new Dict();
		if (!resume.getWorkYear().equals(workYear)) {
			resume.setWorkYear(workYear);
			
			dictSearchVo.setId(resume.getWorkYear());
			Dict oldDict = dictService.selectOne(dictSearchVo);
			String oldName = "";
			if (oldDict != null) oldName = oldDict.getName();
			
			dictSearchVo.setId(workYear);
			Dict newDict = dictService.selectOne(dictSearchVo);
			String newName = "";
			if (newDict != null) newName = newDict.getName();
			resumeLogRemark.append("工作经验" + oldName + "改为" + newName + "</BR>");
		}
		
		if (resume.getProvinceId() != provinceId) {
			resume.setProvinceId(provinceId);
						
			dictSearchVo.setId(resume.getProvinceId());
			Dict oldDict = dictService.selectOne(dictSearchVo);
			String oldName = "";
			if (oldDict != null) oldName = oldDict.getName();
			
			dictSearchVo.setId(provinceId);
			Dict newDict = dictService.selectOne(dictSearchVo);
			String newName = "";
			if (newDict != null) newName = newDict.getName();
			resumeLogRemark.append("户口省份" + oldName + "改为" + newName + "</BR>");
			
			
		}
		
		if (!resume.getCityId().equals(cityId)) {
			resume.setCityId(cityId);	
			dictSearchVo.setId(resume.getCityId());
			Dict oldDict = dictService.selectOne(dictSearchVo);
			String oldName = "";
			if (oldDict != null) oldName = oldDict.getName();
			dictSearchVo.setId(cityId);
			Dict newDict = dictService.selectOne(dictSearchVo);
			String newName = "";
			if (newDict != null) newName = newDict.getName();
			resumeLogRemark.append("户口城市" + oldName + "改为" + newName + "</BR>");
		}
		
		if (StringUtil.isEmpty(hukou)) {
			if (provinceId > 0) {
				hukou+= dictService.getDictName(provinceId);
			}
			if (cityId > 0) {
				hukou+= " " + dictService.getDictName(cityId);
			}
		}
		
		if (!StringUtil.isEmpty(hukou)) {
			String[] hukouAry = StringUtil.convertStrToArrayByDelimiter(hukou, " ");
			if (provinceId == 0) {
				String provinceName = hukouAry[0];
				provinceId = dictService.getIdByName(Constants.DICT_PROVICE, provinceName);
				if (provinceId > 0) resume.setProvinceId(provinceId);
			}
			
			if (cityId == 0) {
				String cityName = hukouAry[1];
				cityId = dictService.getIdByName(Constants.DICT_CITY, cityName);
				if (cityId > 0) resume.setCityId(cityId);
			}
		}
		
		resume.setHukou(hukou);
		
		if (!StringUtil.isEmpty(idCard) && !resume.getIdCard().equals(idCard)) {
			resume.setIdCard(idCard);
			resumeLogRemark.append("身份证号" + resume.getIdCard() + "改为" + idCard + "</BR>");
			
			//根据身份证号计算出年龄
			IdcardInfoExtractor ie = new IdcardInfoExtractor(idCard);
			Integer age = ie.getAge();
			resume.setAge(age);
			
			totalScore = totalScore + Constants.SCORE_COMPLETE_IDCARD;
			resume.setTotalScore(totalScore);
		}
		
		if (!resume.getAddr().equals(addr)) {
			resume.setAddr(addr);
			resumeLogRemark.append("常住地址" + resume.getAddr() + "改为" + addr + "</BR>");
		}
		
		if (!resume.getRemark().equals(remark)) {
			resume.setRemark(remark);
			resumeLogRemark.append("自我介绍有修改</BR>");
		}
		
		if (hopeSalary > 0 && !resume.getHopeSalary().equals(hopeSalary)) {
			resume.setHopeSalary(hopeSalary);
		}
		
		if (nationId > 0 && !resume.getNationId().equals(nationId)) {
			resume.setNationId(nationId);
		}
		
		if (degreeId > 0 && !resume.getDegreeId().equals(degreeId)) {
			resume.setDegreeId(degreeId);
		}
		
		resume.setServiceCanDate(serviceCanDate);
		//信息完整度
//		if (!StringUtil.isEmpty(resumeLogRemark.toString())) {
			Integer totalComplete = resumeScoreService.getTotalComplete(resume);
			resume.setTotalComplete(totalComplete);
			resume.setUpdateTime(nowTime);
			resumeService.update(resume);
//		}
		
		
		//处理服务技能, 判断是否需要更新，并且记录更新日志
		if (!StringUtil.isEmpty(serviceTypes)) {
			ResumeSkill resumeSkillSearchVo = new ResumeSkill();
			resumeSkillSearchVo.setResumeId(resumeId);
			List<ResumeSkill> resumeSkills = resumeSkillService.selectBySearchVo(resumeSkillSearchVo, "id desc");
			String oldServiceTypes = "";
			String oldServiceTypeNames = "";
			for (ResumeSkill oldResumeSkill : resumeSkills) {
				oldServiceTypes+= oldResumeSkill.getSkillId().toString() + ",";
				
				Dict serviceType = dictService.selectByPrimaryKey(oldResumeSkill.getSkillId());
				oldServiceTypeNames+= serviceType.getName() + ",";
			}
			
			String[] oldServiceTypeAry = StringUtil.convertStrToArray(oldServiceTypes);
			String[] newServiceTypeAry = StringUtil.convertStrToArray(serviceTypes);
			Boolean hasUpdate = false;
			
			if (oldServiceTypeAry.length == 0 && newServiceTypeAry.length > 0) {
				hasUpdate = true;
			} else {
				Arrays.sort(oldServiceTypeAry);
				Arrays.sort(newServiceTypeAry);
				if (Arrays.equals(oldServiceTypeAry, newServiceTypeAry) == false) {
					hasUpdate = true;
				}
			}
			
			
			if (hasUpdate) {
				String newServiceTypeNames = "";
				resumeSkillService.delete(resumeSkillSearchVo);
				int len = newServiceTypeAry.length;
				for (int i = 0 ; i < len; i++) {
					String serviceTypeIdStr = newServiceTypeAry[i];
					if (StringUtil.isEmpty(serviceTypeIdStr)) continue;
					Integer serviceTypeId = Integer.valueOf(serviceTypeIdStr);
					ResumeSkill resumeSkill = resumeSkillService.initPo(new ResumeSkill());
					resumeSkill.setResumeId(resumeId);
					resumeSkill.setResumeNo(resumeNo);
					resumeSkill.setSkillId(serviceTypeId);
					resumeSkill.setAddTime(nowTime);
					resumeSkillService.insert(resumeSkill);
					
					Dict serviceType = dictService.selectByPrimaryKey(serviceTypeId);
					newServiceTypeNames+= serviceType.getName() + ",";
				}
				
				resumeLogRemark.append("技能" + oldServiceTypeNames + "改为" + newServiceTypeNames + "</BR>");
			}
		}
		
		//处理服务区域
		if (!StringUtil.isEmpty(regionids)) {
			ResumeServiceArea resumeServiceAreaSearchVo = new ResumeServiceArea();
			resumeServiceAreaSearchVo.setResumeId(resumeId);
			List<ResumeServiceArea> resumeServiceAreas = resumeServiceAreaService.selectBySearchVo(resumeServiceAreaSearchVo, "id desc");
			
			String oldServiceRegionIds = "";
			String oldServiceRegionNames = "";
			for (ResumeServiceArea resumeServiceArea : resumeServiceAreas) {
				oldServiceRegionIds+= resumeServiceArea.getRegionId().toString() + ",";
				
				Dict serviceType = dictService.selectByPrimaryKey(resumeServiceArea.getRegionId());
				if (serviceType != null)
				oldServiceRegionNames+= serviceType.getName() + ",";
			}
			
			String[] oldServiceRegionIdAry = StringUtil.convertStrToArray(oldServiceRegionIds);
			String[] newServiceRegionIdAry = StringUtil.convertStrToArray(regionids);
			Boolean hasUpdate = false;
			
			if (oldServiceRegionIdAry.length == 0 && newServiceRegionIdAry.length > 0) {
				hasUpdate = true;
			} else {
				Arrays.sort(oldServiceRegionIdAry);
				Arrays.sort(newServiceRegionIdAry);
				if (Arrays.equals(oldServiceRegionIdAry, newServiceRegionIdAry) == false) {
					hasUpdate = true;
				}
			}
			
			if (hasUpdate) {
				resumeServiceAreaService.delete(resumeServiceAreaSearchVo);
				int len = newServiceRegionIdAry.length;
				String newServiceRegionNames = "";
				for (int i = 0 ; i < len; i++) {
					String regionIdStr = newServiceRegionIdAry[i];
					if (StringUtil.isEmpty(regionIdStr)) continue;
					Integer serviceRegionId = Integer.valueOf(regionIdStr);
					ResumeServiceArea serviceArea = resumeServiceAreaService.initPo(new ResumeServiceArea());
					serviceArea.setResumeId(resumeId);
					serviceArea.setResumeNo(resumeNo);
					serviceArea.setProvinceId(serviceProvinceId);
					serviceArea.setCityId(serviceCityId);
					serviceArea.setRegionId(serviceRegionId);
					serviceArea.setAddTime(nowTime);
					resumeServiceAreaService.insert(serviceArea);
					
					Dict serviceType = dictService.selectByPrimaryKey(serviceRegionId);
					newServiceRegionNames+= serviceType.getName() + ",";
				}
				
				resumeLogRemark.append("服务区域" + oldServiceRegionNames + "改为" + newServiceRegionNames + "</BR>");
			}
		}
		
		//人才库日志
		if (!StringUtil.isEmpty(resumeLogRemark.toString())) {
			ResumeLog resumeLog = resumeLogService.initPo(new ResumeLog());
			resumeLog.setResumeId(resumeId);
			resumeLog.setResumeNo(resumeNo);
			resumeLog.setLogType(Constants.LOG_TYPE_UPDATE);
			String logTypeName = ResumeUtil.getLogTypeName(Constants.LOG_TYPE_UPDATE);
			resumeLog.setLogName(logTypeName);
			resumeLog.setActionId(fromId);
			resumeLog.setActionName(fromName);
			resumeLog.setRemark(resumeLogRemark.toString());
			resumeLog.setAddTime(nowTime);
			resumeLogService.insert(resumeLog);
		}
		
		
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("resumeId", resumeId);
		data.put("resumeNo", resumeNo);
		
		//总数
		ResumeSearchVo resumeSearchVo = new ResumeSearchVo();
		Integer total = resumeService.selectCountBySearchVo(resumeSearchVo);
		
		//排名
		Integer rowNum = resumeService.selectByRowNum(resumeId);
		
		data.put("total", total);
		data.put("rowNum", rowNum);
		data.put("totalScore", resume.getTotalScore());
		
		result.setData(data);		
		return result;
	}
	
	/**
	 * 
	 * 签订合同后，将状态变为上户
	 * @param resumeNo
	 * @param status
	 * @param actionId
	 * @param actionName
	 * @param actionMobile
	 * @return result
	 * */
	@RequestMapping(value = "/api/resume/setStatus.json", method = RequestMethod.POST)
	public AppResultData<Object> setStatus(
			@RequestParam("resumeNo") String resumeNo,
			@RequestParam("status") Integer status,
			@RequestParam(value = "actionId", required = false, defaultValue = "0") Integer actionId,
			@RequestParam(value = "actionName", required = false, defaultValue = "") String actionName,
			@RequestParam(value = "actionMobile", required = false, defaultValue = "") String actionMobile) {
		AppResultData<Object> result = new AppResultData<Object>(Constants.SUCCESS_0, "ok", "");
		
		Resume searchVo = new Resume();
		searchVo.setResumeNo(resumeNo);
		Resume resume = resumeService.selectOne(searchVo);
		if (resume == null) {
			result.setStatus(Constants.ERROR_999);
			result.setMsg("人才信息不存在");
			return result;
		}
		Integer resumeId = resume.getResumeId();
		
		resume.setStatus(status);
		resume.setUpdateTime(TimeStampUtil.getNowSecond().intValue());
		resumeService.update(resume);
		
		ResumeLog resumeLog = resumeLogService.initPo(new ResumeLog());
		resumeLog.setResumeId(resumeId);
		resumeLog.setResumeNo(resumeNo);
		resumeLog.setLogType(Constants.LOG_TYPE_CONTRACT);
		String logTypeName = ResumeUtil.getLogTypeName(Constants.LOG_TYPE_CONTRACT);
		resumeLog.setLogName(logTypeName);
		resumeLog.setActionId(actionId);
		resumeLog.setActionName(actionName);
		resumeLog.setRemark("订单签约，状态改为上户状态");
		resumeLog.setAddTime(TimeStampUtil.getNowSecond().intValue());
		resumeLogService.insert(resumeLog);
		
		return result;
	}
	
	/**
	 * 
	 * 用户分享给好友后，状态变为已推荐状态
	 * @param resumeNo
	 * @param resumeId
	 * @param publish
	 * @param actionId
	 * @param actionName
	 * @param actionMobile
	 * @return result
	 * */
	@RequestMapping(value = "/api/resume/setPublish.json", method = RequestMethod.POST)
	public AppResultData<Object> setPublic(
			@RequestParam(value = "resumeNo", required = false, defaultValue = "") String resumeNo,
			@RequestParam(value = "resumeId", required = false, defaultValue = "0") Integer resumeId,
			@RequestParam(value = "publish", required = false, defaultValue = "1") Integer publish,
			@RequestParam(value = "actionId", required = false, defaultValue = "0") Integer actionId,
			@RequestParam(value = "actionName", required = false, defaultValue = "") String actionName,
			@RequestParam(value = "actionMobile", required = false, defaultValue = "") String actionMobile) {
		AppResultData<Object> result = new AppResultData<Object>(Constants.SUCCESS_0, "ok", "");
		
		Resume searchVo = new Resume();
		if (StringUtil.isEmpty(resumeNo) && resumeId == 0) {
			return result;
		}
		
		if (!StringUtil.isEmpty(resumeNo)) searchVo.setResumeNo(resumeNo);
		if (resumeId > 0) searchVo.setResumeId(resumeId);
		
		Resume resume = resumeService.selectOne(searchVo);
		if (resume == null) {
			result.setStatus(Constants.ERROR_999);
			result.setMsg("人才信息不存在");
			return result;
		}
		
		Integer oldPublish = resume.getPublish();
		
		//如果已经设置过已推荐，则不需要再次设置为已推荐了。
		if (oldPublish == 1) return result;
		
		if (StringUtil.isEmpty(resumeNo)) resumeNo = resume.getResumeNo();
		if (resumeId == 0) resumeId = resume.getResumeId();
		
		resume.setPublish(publish);
		resume.setUpdateTime(TimeStampUtil.getNowSecond().intValue());
		resumeService.update(resume);
		
		ResumeLog resumeLog = resumeLogService.initPo(new ResumeLog());
		resumeLog.setResumeId(resumeId);
		resumeLog.setResumeNo(resumeNo);
		resumeLog.setLogType(Constants.LOG_TYPE_RESUME_PUBLISH);
		String logTypeName = ResumeUtil.getLogTypeName(Constants.LOG_TYPE_CONTRACT);
		resumeLog.setLogName(logTypeName);
		resumeLog.setActionId(actionId);
		resumeLog.setActionName(actionName);
		resumeLog.setRemark("已被老师推荐给用户");
		resumeLog.setAddTime(TimeStampUtil.getNowSecond().intValue());
		resumeLogService.insert(resumeLog);
		
		return result;
	}
	
	

}